import requests
import json
import time
import sys
import traceback
import dbHelper

# INSERT INTO gao_kao.raw_score_line
# ( score, score_section, major_score, batch, batch_name, `type`, type_name, province, `year`, diff, `rank`)
# VALUES('', '', '', '', '', '', '', '', '', '', '')

# db = DBManager(host='39.104.16.196',
#                      user='gk',
#                      password='qwertyQWERTY@123',
#                      database='gao_kao')

# db = DBHelper.defaultInstance()
db = dbHelper.defaultInstance()

version = db.execute("SELECT VERSION()")
print(version)

def handle(data, num):
    
    key = "t_" + str(num)
    if key not in data:
        print("ignore {}".format(key))
        return
    
    t = data[key]
    for i in range(0, len(t)):
        tData = t[i]
        print("batch_name" + tData["batch_name"])
        print("score" + tData["score"])
        print("INSERT INTO gao_kao.raw_score_line( score, score_section, major_score, batch, batch_name, `type`, type_name, province, `year`, diff, `rank`)" 
                   + " VALUES({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})"
                   .format(tData["score"], tData["score_section"], tData["major_score"], tData["batch"], tData["batch_name"]
                           ,tData["type"],tData["type_name"],tData["province"],tData["year"],tData["diff"],tData["rank"]))
        
        db.execute("INSERT INTO gao_kao.raw_score_line( score, score_section, major_score, batch, batch_name, `type`, type_name, province, `year`, diff, `rank`)" 
                   + " VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')"
                   .format(tData["score"], tData["score_section"], tData["major_score"], tData["batch"], tData["batch_name"]
                           ,tData["type"],tData["type_name"],tData["province"],tData["year"],tData["diff"],tData["rank"]))


for i in range(1, 90):
    try:
        time.sleep(10)
        print("########################### " + str(i))
        resp = requests.get("https://static-data.gaokao.cn/www/2.0/proprovince/" + str(i) +"/pro.json")
        respDic = resp.json()
        if respDic["code"] != "0000":
            print("failed")

        data = respDic["data"]
        
        for year in range(2014, 2024):
            for num in range(1, 10):
                handle(data=data[str(year)], num=num)
            
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info() 
        print('traceback.format_exc():\n%s' % traceback.format_exc())
        continue




# print(respDic['data'])

# jsonStr = json.dumps(resp.json())
